import java.util.Arrays;

/**
 * Created by losor on 2017/3/24.
 */
public class _532_KdiffPairsInArray {
    public static void main(String[] args) {
        _532_KdiffPairsInArray a = new _532_KdiffPairsInArray();
        int[] b = new int[]{3,1,4,1,5};
        System.out.println(a.findPairs(b,2));
    }

    public int findPairs(int[] nums, int k) {
        Arrays.sort(nums);
        int index = 1;
        int count = 0;
        if(k == 0) {
            while(index < nums.length){
                if (nums[index] == nums[index - 1]) {
                    count++;
                    while (index < nums.length && nums[index] == nums[index - 1]) {
                        index++;
                    }
                } else {
                    index++;
                }
            }
            return count;
        }
        index = 0;
        int i = 1;
        while (index<nums.length && i < nums.length) {
            if (nums[i] == nums[i-1]){
                i++;
                continue;
            }
            if (Math.abs(nums[i] - nums[index]) == k){
                count++;
                index++;
                i++;
            }else if (Math.abs(nums[i] - nums[index])> k ){

                while(index+1<nums.length && nums[index] == nums[index+1]){
                    index++;
                }
                index++;
            }
            else{
                i++;
            }
        }
        return count;
    }
}
